package com.mtgg.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.mtgg.common.PageBean;
import com.mtgg.common.response.ServerResponse;
import com.mtgg.dao.TestDao;
import com.mtgg.dto.UserDto;
import com.mtgg.entity.User;
import com.mtgg.req.UserReq;
import com.mtgg.service.TestService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
@Service
public class TestServiceImpl extends ServiceImpl<TestDao, User> implements TestService {

    @Autowired
    private TestDao testDao;


    @Override
    public List<User> getUsers() {
        return testDao.getUsers();
    }

    @Override
    public ServerResponse getByCondition(UserReq userReq) {
        User user = new User();
        BeanUtils.copyProperties(userReq, user);
//        QueryWrapper<User> queryWrapper = new QueryWrapper();
//        queryWrapper.lambda().eq(User::getName, "");
        return ServerResponse.createBySuccess(testDao.selectList(new QueryWrapper<>(user)));
    }

    /**
     * @Author: 亦善
     * @Date: 2020/5/15 17:01
     * @Describe: pagehelper使用示例
     */
    @Override
    public ServerResponse getPage(UserReq userReq, Integer currentPage, Integer pageSize) {
        //输入页数
        PageHelper.startPage(currentPage, pageSize);
        //此处可以根据前端来判断设置
        PageHelper.orderBy("id desc");
        //mybatis-plus查询
        List<User> list = testDao.selectList(new QueryWrapper<>(userReq.req2Entity()));
        if (CollUtil.isEmpty(list)) {
            return ServerResponse.createBySuccess(list);
        }
        //将与数据库对应的映射转为dto返回给客户端
        List<UserDto> dtos = Lists.newArrayListWithCapacity(list.size());
        //lambda
        list.forEach(x->dtos.add(x.entity2DTO()));
        //结果整理
        PageInfo pageInfo = new PageInfo(dtos);
        //自定义bean返回给客户端
        PageBean pageBean = PageBean.info2Page(pageInfo);
        return ServerResponse.createBySuccess(pageBean);
    }
}
